package com.mindcraft.user.api;


import com.alibaba.fastjson.JSONObject;
import com.mindcraft.base.handle.MindCraftException;
import com.mindcraft.base.model.MindCraftResult;
import com.mindcraft.base.utils.*;
import com.mindcraft.user.po.McUser;
import com.mindcraft.user.serivce.XcxService;
import com.mindcraft.user.utils.ConstantPropertiesUtil;
import com.mindcraft.user.utils.HttpClientUtils;
import com.mindcraft.user.vo.UserLoginVo;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Controller;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@Slf4j
@RestController
@RequestMapping("/user/weixin")
@Api(value = "user", tags = "微信小程序")
public class XcxWXLoginController {


    @Autowired
    private XcxService xcxUserService;

    @Autowired
    private RedisTemplate redisTemplate;


    @ApiOperation(value = "微信登录获取openid(小程序)")
    @GetMapping("/wxLogin/{code}")
    public MindCraftResult callback(@PathVariable String code) {
        //获取授权临时票据
        System.out.println("微信授权服务器回调。。。。。。" + code);
        if (StringUtils.isEmpty(code)) {
            throw new MindCraftException("微信登录获取code失败");
        }

        //使用code和appid以及appscrect换取access_token
        StringBuffer baseAccessTokenUrl = new StringBuffer()
                .append("https://api.weixin.qq.com/sns/jscode2session")
                .append("?appid=%s")
                .append("&secret=%s")
                .append("&js_code=%s")
                .append("&grant_type=authorization_code");

        String accessTokenUrl = String.format(baseAccessTokenUrl.toString(),
                ConstantPropertiesUtil.WX_OPEN_APP_ID,
                ConstantPropertiesUtil.WX_OPEN_APP_SECRET,
                code);

        String result = null;
        try {
            result = HttpClientUtils.get(accessTokenUrl);
        } catch (Exception e) {
            throw new MindCraftException("微信登录失败");
        }

        System.out.println("使用code换取的access_token结果 = " + result);
        JSONObject resultJson = JSONObject.parseObject(result);
        if (resultJson.getString("errcode") != null) {
            throw new MindCraftException("微信登录失败");
        }

        String accessToken = resultJson.getString("session_key");
        String openId = resultJson.getString("openid");

        // 为了测试，openId写固定
//        String accessToken = "";
//        String openId = "odo3j4uGJf6Hl2FopkEOLGxr7LE4";

        //根据access_token获取微信用户的基本信息
        //先根据openid进行数据库查询
        McUser user = xcxUserService.getByOpenid(openId);
        // 如果没有查到用户信息,那么调用微信个人信息获取的接口
        String userToken = "";
        String uuid = UUID.randomUUID().toString().replaceAll("-", "");
        if (null == user) {

            user = new McUser();
            user.setId(uuid);
            user.setUsername(openId);
            user.setOpenId(openId);
            user.setNickname(openId);
            user.setUserpic("");
            user.setUtype("101001");
            xcxUserService.save(user);
        }

        Map<String, Object> map = new HashMap<>();
        String name = user.getNickname();
        map.put("user", user);

        String token = JwtHelper.createToken(user.getId(), name);
        map.put("token", token);


//        if (!redisTemplate.hasKey(CommonConst.USER_TOKEN + user.getId())) {
//            String userId = user.getId();
//            userToken = CommonConst.USER_ACCESS_TOKEN + userId;
//            UserLoginVo userLoginVo = xcxUserService.getUserLoginVo(user.getId());
//            redisTemplate.opsForValue().set(userToken, userLoginVo, CommonConst.TOKEN_EXPIRE, TimeUnit.SECONDS);
//            redisTemplate.opsForValue().set(
//                    CommonConst.USER_TOKEN + userId,
//                    userToken, CommonConst.TOKEN_EXPIRE, TimeUnit.SECONDS);
//        }
        String userId = user.getId();
        if(!redisTemplate.hasKey(CommonConst.USER_TOKEN_JWT+ userId)){
            redisTemplate.opsForValue().set(CommonConst.USER_TOKEN_JWT+ userId,token,CommonConst.TOKEN_EXPIRE, TimeUnit.SECONDS);
        }


        return MindCraftResult.success(map);
    }

    @PostMapping("/auth/updateUser")
    @ApiOperation(value = "更新用户昵称与头像")
    public MindCraftResult updateUser(@RequestHeader("token") String token, @RequestBody McUser user) {
        String userId = JwtHelper.getUserId(token);
        McUser user1 = xcxUserService.getById(userId);
        //把昵称更新为微信用户
        user1.setNickname(user.getNickname().replaceAll("[ue000-uefff]", "*"));
        user1.setUsername(user.getNickname());
        user1.setUserpic(user.getUserpic());
        xcxUserService.updateById(user1);
        return MindCraftResult.success(user1);
    }

}
